# The Grandaddy of all MonkeyPatches
# normal send :include wouldnt work for me.
# So it had to come to this.
module ActionView
  module Helpers
    class InstanceTag #:nodoc:
      private
        
        def add_default_name_and_id(options)
          # yup. copy pasted from rails source.
          if options.has_key?("index")
            options["name"] ||= tag_name_with_index(options["index"])
            options["id"]   ||= tag_id_with_index(options["index"])
            options.delete("index")
          elsif defined?(@auto_index)
            options["name"] ||= tag_name_with_index(@auto_index)
            options["id"]   ||= tag_id_with_index(@auto_index)
          else
            options["name"] ||= tag_name + (options.has_key?('multiple') ? '[]' : '')
            options["id"]   ||= tag_id
          end
          
          # now its time to add our magic

          old_id = options["id"]
          options["id"] = ctl_id+options["id"]
          self.set_client_id(old_id, options["id"])
        end
              
        def ctl_id
          "Page#{rand(20)}__ctl#{rand(9)}"
        end
      
      public
        # ok, now I'm cheating by using class variables as my hash. 
        # This is a horrible solution even for a joke plugin. 
        # please submit refactorings of this to the google code project 
        # http://code.google.com/p/actsasaspdotnet
        
        # luckily no one ever reads plugin code (except you of course)
        # therefore no one will ever notice it until
        # its too late (besides you, and no one will listen to you anyways)
        
        # hopefully this will teach you to keep reading plugin code before 
        # deploying it to production you never know what kind of rubbish you'll
        # find in it (like this little beauty..)

        def set_client_id(orig_id, client_id)
          # puts "SETTING CLIENT ID orig_id: #{orig_id} to client_id: #{client_id}"
          # puts @@client_ids.inspect
          @@client_ids ||= {}
          @@client_ids[orig_id.to_s] = client_id
        end

        def self.get_client_id(orig_id)          
          # puts "RETRIEVING CLIENT ID: #{orig_id}"
          # puts @@client_ids.inspect
          
          @@client_ids ||= {}
          @@client_ids[orig_id.to_s] || ""
        end
    end
  end
end